package com.ruoyi.workflow.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.domain.vo.DoneTaskVo;
import com.ruoyi.workflow.mapper.CarPackageAuditMapper;
import com.ruoyi.workflow.service.IDoneTaskService;
import com.ruoyi.workflow.util.ActivitiUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.workflow.constant.AuditConstant.SI_AUDIT_STATUS_REVIEW;

/**
 * 已办任务业务层
 */
@Service
public class DoneTaskServiceImpl implements IDoneTaskService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;


    /**
     * 查询已办任务
     * @param params 根据日期时间搜索
     * @return
     */
    @Override
    public TableDataInfo done(Map<String, Object> params) {
        //封装响应数据
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");

        //1.获取用户名
        String username = SecurityUtils.getUsername();
        //2.根据用户名作为负责人查询已办任务个数
        long doneTaskTotal = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(username).count();
        //3.如果已办任务个数为0，则直接返回
        tableDataInfo.setTotal(doneTaskTotal);
        if(doneTaskTotal == 0){
            tableDataInfo.setRows(Collections.EMPTY_LIST);
            return tableDataInfo;
        }
        //4.获取分页的数据：当前页，每页多少条数据
        //接受请求的分页的数据
        PageDomain pageDomain = TableSupport.buildPageRequest();
        //5.计算分页起始索引
        int startIndex = (pageDomain.getPageNum()-1)* pageDomain.getPageSize();
        //6.根据用户名获取所有已办任务
        List<DoneTaskVo> todoTaskVoList = new ArrayList<>();
        List<HistoricTaskInstance> doneTaskList = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(username).orderByHistoricTaskInstanceEndTime().desc().listPage(startIndex, pageDomain.getPageSize());
        //7.封装数据
        doneTaskList.forEach(item->{
            //7.1 通过流程实例获取businessKey
            String businessKey = ActivitiUtils.getBusinessKeyByHistoryProcessInstanceId(item.getProcessInstanceId());
            //7.2 根据businessKey查询审核套装的信息
            CarPackageAudit carPackageAudit = carPackageAuditMapper.selectCarPackageAuditById(Long.valueOf(businessKey),params);
            if(carPackageAudit != null){
                //判断审核流程是否结束，如果结束，则无审核人，只有审核中才用 当前审核人
                List<String> candidateUsers = new ArrayList<>();
                if ((SI_AUDIT_STATUS_REVIEW.equals(carPackageAudit.getStatus()))) {
                    //7.3 查询候选人的名字 即 当前审核人
                    //问题：但是目前的任务已经审批通过，进入到下个任务节点，此时如果用当前任务的ID查，则会报空指针异常.
                    //原因：查询运行的表，只能是当前节点，如果该节点已经审核通过后，进入下个节点，上个节点就会查不到，要查只能到历史的表查。
                    //获取下个任务节点
                    Task task = taskService.createTaskQuery().processInstanceId(item.getProcessInstanceId()).singleResult();
                    List<String> userNames = taskService
                            .getIdentityLinksForTask(task.getId())
                            .stream()
                            .map(identityLink -> identityLink.getUserId())
                            .collect(Collectors.toList());
                    candidateUsers = sysUserMapper.selectNickNameByBatchUserName(userNames);
                }
                //封装每条审批任务
                DoneTaskVo doneTaskVo = new DoneTaskVo();
                BeanUtils.copyBeanProp(doneTaskVo,carPackageAudit);
                //已办任务名称
                doneTaskVo.setDoneTaskName(item.getName());
                //任务完成时间
                doneTaskVo.setDoneTaskDateTime(item.getEndTime());
                //当前审核人
                doneTaskVo.setCandidateUserList(candidateUsers);
                todoTaskVoList.add(doneTaskVo);
            }
        });
        tableDataInfo.setRows(todoTaskVoList);
        return tableDataInfo;
    }
}
